package com.clei.netty.sync.client;

import com.clei.consts.NettyConstants;
import com.clei.netty.file.enums.FileSyncCmdTypeEnum;
import com.clei.netty.sync.dto.ClientParam;
import com.clei.netty.sync.dto.MsgBody;
import com.clei.utils.PrintUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.File;

/**
 * file sync client
 * 文件同步客户端
 *
 * @author Y
 * @date 2024-08-14
 */
public class FileSyncClient {

    public static void main(String[] args) {
        if (null == args || args.length < 3) {
            args = new String[]{NettyConstants.SERVER_IP, "E:\\Temp", "E:\\TempTemp"};
        }
        String serverIp = args[0];
        String serverFilePath = args[1];
        String clientFilePath = args[2];

        File file = new File(clientFilePath);
        if (file.exists()) {
            if (file.isFile()) {
                PrintUtil.log("客户端文件路径错误，文件已存在");
            }
        } else {
            file.mkdirs();
        }
        PrintUtil.log("File Sync Client 启动 serverIp : {}, serverFilePath : {}, clientFilePath : {}",
                serverIp, serverFilePath, clientFilePath);
        // 启动
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        ClientParam clientParam = new ClientParam(bossGroup, clientFilePath);
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(bossGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new FileSyncClientInitializer(clientParam));
            // 连接
            Channel channel = bootstrap.connect(serverIp, NettyConstants.SERVER_PORT).sync().channel();
            // 请求同步
            int seq = clientParam.getSeqCounter().incrementAndGet();
            byte[] data = serverFilePath.getBytes(NettyConstants.DEFAULT_CHARSET);
            channel.writeAndFlush(new MsgBody(seq, 0, FileSyncCmdTypeEnum.REQ_SYNC.getCmdCode(), data));
        } catch (Exception e) {
            PrintUtil.log(e);
        }
    }
}
